package com.gofaraway.service.student.leetcode100.链表;

import com.gofaraway.service.student.leetCodeV2.验证回文串.ListNode;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * https://leetcode.cn/problems/intersection-of-two-linked-lists/description/?envType=study-plan-v2&envId=top-100-liked
 *
 * @author ChenPeng
 * @date 2025/9/13 14:27
 */
public class 相交链表 {


    /**
     * 双指针解法
     * 思路：我走过你走过的路 只为与你相拥

     */
    public ListNode getIntersectionNode_B(ListNode headA, ListNode headB) {
//如果headA headB任意一个为null 则必不可能相交 返回null
        if (headB == null || headA == null) {
            return null;
        }
        ListNode pA = headA;
        ListNode pB = headB;
        while (pA != pB) {
            //如果第一个指针 遍历完了，那么直接指向 headB 重走第二个指针走过的路 只为相遇
            if (pA == null) {
                pA = headB;
            } else {
                pA = pA.next;
            }

            //如果第二个指针 遍历完了，那么同理 ：直接指向 headA， 重走第一个指针走过的路 只为相遇
            if (pB == null) {
                pB = headA;
            } else {
                pB = pB.next;
            }
        }

        //不论是否相交 都是返回pA即可
        return pA;
    }

    /**
     * 暴力解法 利用字典解
     * 不推荐
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> dic = new HashSet<>();
        ListNode temp = headA;
        while (temp != null) {
            dic.add(temp);
            temp = temp.next;
        }


         temp = headB;
        while (temp != null) {
            if (dic.contains(temp)) {
                return temp;
            }
            temp = temp.next;
        }
        return null;
    }

    public class ListNode {

        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
